﻿global using Microsoft.Extensions.Logging;

global using System.Diagnostics;

using Microsoft.Extensions.Hosting;

namespace MPNet6.Server;
public class MPHostedService : IHostedService
{
    private readonly int _Port;
    private readonly ILogger _Logger;
    private Func<List<MPClientMessage>>? _GetMsgs;
    private Action<List<MPClientMessage>>? _SaveMessage;

    public MPHostedService(int port, Func<List<MPClientMessage>>? getClientMessages, Action<List<MPClientMessage>>? saveClientrMessages, ILogger logger)
    {
        _Logger = logger;
        _Port = port;
        _GetMsgs = getClientMessages;
        _SaveMessage = saveClientrMessages;
    }
    public Task StartAsync(CancellationToken cancellationToken)
    {
        _Logger.Log(LogLevel.Information, $"MPServer start...");
        Stopwatch sw = Stopwatch.StartNew();
        var msgs = _GetMsgs?.Invoke();
        MPServer.Start(_Port, msgs, _Logger);
        _Logger.Log(LogLevel.Information, $"MPServer started in {sw.ElapsedMilliseconds}ms, {msgs?.Count ?? 0} clients inited,Listening on :{_Port}");
        return Task.CompletedTask;
    }


    public Task StopAsync(CancellationToken cancellationToken)
    {
        _Logger.Log(LogLevel.Information, $"MPServer stopping...");
        Stopwatch sw = Stopwatch.StartNew();
        _SaveMessage?.Invoke(MPServer.Stop());
        _Logger.Log(LogLevel.Information, $"MPServer stopped in {sw.ElapsedMilliseconds}ms.");
        return Task.CompletedTask;
    }
}

